#!/user/bin/env python3
# -*- coding: utf-8 -*-
import pytest, time, allure
from common.loggers import Logger
from common.oper_yaml import OperYaml
from common.screen_recordings import PcScreen, MobileScreen

import pyscreenrec


@pytest.fixture(scope="function", autouse=True)
def screencap_mobile():  # 手机录屏
    now = time.strftime("%y%m%d%H%M%S", time.localtime())
    images_path = f'./images/{now}_mobile.mp4'
    MS = MobileScreen(images_path=images_path)
    MS.start()

    yield

    MS.stop()

    allure.attach.file(images_path, name='录屏',
                       attachment_type=allure.attachment_type.MP4)  # 测试步骤中添加一张图片或视频


@pytest.fixture(scope="function", autouse=True)
def screencap_pc():  # pc录屏
    now = time.strftime("%y%m%d%H%M%S", time.localtime())
    images_path = f'./images/{now}_pc.mp4'
    PR = PcScreen(images_path=images_path)
    PR.start()

    yield

    PR.stop()

    allure.attach.file(images_path, name='录屏',
                       attachment_type=allure.attachment_type.MP4)  # 测试步骤中添加一张图片或视频

    # for path in [images_path]:
    #     # with open(path, "rb") as f:
    #     #     allure.attach(f.read(), name='录屏', attachment_type=allure.attachment_type.MP4)
    #     allure.attach.file(path, name='录屏',
    #                        attachment_type=allure.attachment_type.MP4)  # 测试步骤中添加一张图片或视频
    #     # Logger.error('添加视频')
    #


# @pytest.fixture(scope="function", autouse=True)
# def screencap2():
#     now = time.strftime("%y%m%d%H%M%S", time.localtime())
#     images_path = f'./images/{now}.mp4'
#     #Install on Windows: pip install pyscreenrec
#     #https://github.com/Shravan-1908/pyscreenrec
#     recorder = pyscreenrec.ScreenRecorder()
#     recorder.start_recording(images_path,16)
#
#     yield
#
#     recorder.stop_recording()
#     # images_path1 = f'./images/20230217160727.avi'
#
#     with allure.step('录屏'):
#         for path in [images_path]:
#             with open(path, "rb") as f:
#                 allure.attach(f.read(), name='录屏', attachment_type=allure.attachment_type.MP4)
#
#         # allure.attach.file(images_path, name='录屏',
#         #                    attachment_type=allure.attachment_type.MP4)  # 测试步骤中添加一张图片或视频


# 命令行传参addoption 在contetest.py添加命令行选项,命令行传入参数”—cmdopt“, 用例如果需要用到从命令行传入的参数，就调用cmdopt函数：
def pytest_addoption(parser):
    parser.addoption("--env", action="store", default="test",
                     help=None)  # env，变量参数名；default  默认参数，如env 没有进行传值，则使用"test"


@pytest.fixture(scope='session')
def cmdopt(pytestconfig):
    # 两种写法
    # global parameter_data
    global url
    url = (pytestconfig.getoption("--env"))
    return url
    # return pytestconfig.option.cmdopt


@pytest.fixture(scope='session')
def env_url(cmdopt):  # 读取数据源文件
    url = cmdopt

    Logger.error(url)

    return url


@pytest.fixture(scope='function')  # ,autouse=True
def front_and_back():
    print('开始测试')
    yield 5
    print('结束执行')


# @pytest.fixture(scope='session')
# def case_yaml(): #request
#     return OperYaml.reda_yaml('./data/yaml_02.yaml')
#
#
@pytest.fixture(params=OperYaml.reda_yaml('./data/yaml_02.yaml'))
def case(request):  # request
    return request.param


def pytest_terminal_summary(terminalreporter):
    """
    收集测试结果
    """
    _PASSED = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    _ERROR = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    _FAILED = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    _SKIPPED = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    _TOTAL = terminalreporter._numcollected
    _TIMES = time.time() - terminalreporter._sessionstarttime
    # Logger.info(f"用例总数: {_TOTAL}")
    # Logger.success(f"通过用例: {_PASSED}")
    # Logger.error(f"异常用例数: {_ERROR}")
    # Logger.error(f"失败用例数: {_FAILED}")
    # Logger.warning(f"跳过用例数: {_SKIPPED}")
    # Logger.info(f"用例执行时长: {round(_TIMES, 2)} s")
    try:
        _RATE = _PASSED / _TOTAL * 100

        _SUCCESS_RATE = round(_RATE, 2)

    except ZeroDivisionError:
        _SUCCESS_RATE = "0.00"
    # Logger.info(f"用例成功率:{_SUCCESS_RATE}")
    result_data_test = {
        "_TOTAL": f"{_TOTAL}",
        '_PASSED': f"{_PASSED}",
        "_ERROR": f" {_ERROR}",
        "_FAILED": f" {_FAILED}",
        "_SKIPPED": f" {_SKIPPED}",
        "_TIMES": f"{round(_TIMES, 2)} s",
        "_SUCCESS_RATE": f"{_SUCCESS_RATE}",
    }
    # ExchangeData.post_pytest_summary(result_data_test)#测试结果添加到变量池
    with open("result.txt", "w") as fp:  # 测试结果保存到本地result.txt
        fp.write("_TOTAL=%s" % _TOTAL + "\n")
        fp.write("_PASSED=%s" % _PASSED + "\n")
        fp.write("_FAILED=%s" % _FAILED + "\n")
        fp.write("_ERROR=%s" % _ERROR + "\n")
        fp.write("_SKIPPED=%s" % _SKIPPED + "\n")
        fp.write("_SUCCESS_RATE=%.2f%%" % _SUCCESS_RATE + "\n")
        fp.write("_TIMES=%.2fs" % _TIMES)
